<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-alert
                title="只能为第三级分类设置相关参数"
                type="warning" show-icon>
            </el-alert>
            <el-row  class="cat_top">
                <el-col>
                    <el-cascader
                        v-model="selectCategroy"
                        :options="CategroyList"
                        :props="categoriespros"
                        @change="selectCategroyChange">
                    </el-cascader>
                </el-col>
            </el-row>
            <el-row>
                <el-col>
                    <el-tabs v-model="activeTabsNamw" @tab-click="handleTabsClick">
                        <el-tab-pane label="动态参数" name="many">
                            <el-button type="primary" :disabled="btnControl" @click="addDialogVisible=true">添加参数</el-button>
                            <el-table :data="manyCateList" border stripe>
                                <el-table-column
                                   type="expand">
                                   <template slot-scope="scope">
                                      <el-tag closable class="showRowTag" v-for="(item,i) in scope.row.attr_vals" :key=i @close="hanleClose(i,scope.row)">{{item}}</el-tag>
                                      <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)"
                                      >
                                      </el-input>
                                      <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                                  </template>
                                </el-table-column>
                                <el-table-column
                                   type="index"
                                   label="#">
                                </el-table-column>
                                <el-table-column
                                    prop="attr_name"
                                    label="参数名称">
                                </el-table-column>
                                 <el-table-column
                                    label="操作">
                                    <template slot-scope="scope">
                                         <el-button size="mini" type="primary" icon="el-icon-edit" @click="editbtn(scope.row)"></el-button>
                                          <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteParam(scope.row)"></el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                        <el-tab-pane label="静态属性" name="only" stripe>
                            <el-button type="primary" :disabled="btnControl" @click="addDialogVisible=true">添加属性</el-button>
                            <el-table :data="onlyCateList" border stripe>
                                   <el-table-column
                                   type="expand">
                                   <template slot-scope="scope">
                                      <el-tag closable class="showRowTag" v-for="(item,i) in scope.row.attr_vals" :key=i @close="hanleClose(i,scope.row)">{{item}}</el-tag>
                                      <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)"
                                      >
                                      </el-input>
                                      <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                                  </template>
                                </el-table-column>
                                <el-table-column
                                   type="index"
                                   label="#">
                                </el-table-column>
                                <el-table-column
                                    prop="attr_name"
                                    label="参数名称">
                                </el-table-column>
                                 <el-table-column
                                    label="操作">
                                    <template slot-scope="scope">
                                         <el-button size="mini" type="primary" icon="el-icon-edit" @click="editbtn(scope.row)"></el-button>
                                         <el-button size="mini" type="danger" icon="el-icon-delete"></el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                    </el-tabs>
                </el-col>
            </el-row>
        </el-card>
        <!-- 添加参数对话框 -->
        <el-dialog
          :title="'添加'+titleText"
          :visible.sync="addDialogVisible"
          width="30%"
          @close="closeDialog"
          >
          <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="80px">
            <el-form-item :label="titleText" prop="attr_name">
              <el-input v-model="addForm.attr_name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addParams">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 修改对话框 -->
        <el-dialog
          :title="'修改'+titleText"
          :visible.sync="editDialogVisible"
          width="30%"
          @close="closeEditDialog"
          >
          <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="80px">
            <el-form-item :label="titleText" prop="attr_name">
              <el-input v-model="editForm.attr_name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editCommitbtn">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  data () {
    return {
      CategroyList: [],
      //   级联选择器配置
      categoriespros: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      selectCategroy: [],
      activeTabsNamw: 'first',
      // 动态属性数据
      manyCateList: [],
      //   静态属性数据
      onlyCateList: [],
      addDialogVisible: false,
      // 添加的参数的表单对象
      addForm: { attr_name: '版式' },
      // 添加参数的表单规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      // 修改对话框
      editForm: { attr_name: '' },
      editDialogVisible: false,
      editFormRef: {},
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      // 当前行的数据
      editRow: [],
      // 控件展开行的添加taps标签显示
      inputVisible: false

    }
  },
  created () {
    this.getCategroyList()
  },
  methods: {
    async getCategroyList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$Message.error('获取商品分类失败')
      }
      this.$Message.success('获取成功')
      this.CategroyList = res.data
    },
    selectCategroyChange () {
      if (this.selectCategroy.length !== 3) {
        this.selectCategroy = []
      }
      this.ByIdCategroy()
    },
    // 根据id查询分类
    async ByIdCategroy () {
      const { data: res } = await this.$http.get(`categories/${this.selectCateId}/attributes`,
        { params: { sel: this.activeTabsNamw } })
      if (res.meta.status !== 200) return this.$Message.error('请求失败')
      //   this.$Message.success('请求成功')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res)
      if (this.activeTabsNamw === 'many') {
        this.manyCateList = res.data
      }
      this.onlyCateList = res.data
    },
    handleTabsClick () {
      this.ByIdCategroy()
    },
    // 监听关闭对话框
    closeDialog () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加参数
    addParams () {
      this.$refs.addFormRef.validate(async value => {
        if (!value) return this.$Message.error('请求失败')
        const { data: res } = await this.$http.post(`categories/${this.selectCateId}/attributes`,
          { attr_name: this.addForm.attr_name, attr_sel: this.activeTabsNamw })
        console.log(res)
        if (res.meta.status !== 201) return this.$Message.error('添加参数失败')
        this.getCategroyList()
        this.addDialogVisible = false
        return this.$Message.success('请求成功')
      })
    },
    closeEditDialog () {
      this.$refs.editFormRef.resetFields()
    },
    // 修改按钮
    editbtn (value) {
      this.editDialogVisible = true
      this.editRow = value
    },
    // 编辑提交修改分类参数
    async editCommitbtn () {
      const { data: res } = await this.$http.put(`categories/${this.selectCateId}/attributes/${this.editRow.attr_id}`,
        { attr_name: this.editForm.attr_name, attr_sel: this.activeTabsNamw })
      console.log(res)
      this.editDialogVisible = false
      if (res.meta.status !== 200) return this.$Message.error('修改参数失败')
      this.$Message.success('修改参数成功')
      this.ByIdCategroy()
      this.editDialogVisible = false
    },
    async deleteParam (value) {
      const { data: res } = await this.$http.delete(`categories/${this.selectCateId}/attributes/${value.attr_id}`)
      if (res.meta.status !== 200) return this.$Message.error('删除参数失败')
      this.$Message.success('删除参数成功')
      this.ByIdCategroy()
    },
    // 展开行按钮
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // tags回车和失去焦点触发的事件
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue)
      row.inputVisible = false
      this.pullAttr(row)
    },
    // 提交参数
    async pullAttr (row) {
      const { data: res } = await this.$http.put(`categories/${this.selectCateId}/attributes/${row.attr_id}`, { attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(' ') })
      if (res.meta.status !== 200) return this.$Message.error('修改标签失败')
      this.$Message.success('修改标签成功')
    },
    // 删除taps标签
    hanleClose (i, row) {
      console.log(i)
      row.attr_vals.splice(i, 1)
      // console.log(row.attr_vals)
      this.pullAttr(row)
    }

  },

  computed: {
    btnControl () {
      if (this.selectCategroy.length !== 3) { return true }
      return false
    },
    // 获取三级分类id
    selectCateId () {
      if (this.selectCategroy.length === 3) { return this.selectCategroy[2] }
      return null
    },
    titleText () {
      if (this.activeTabsNamw === 'many') {
        return '动态参数'
      } else {
        return '静态参数'
      }
    }

  }
}
</script>

<style lang="less" scoped>
.cat_top{
    margin-top: 15px;
}
.input-new-tag{
  width: 100px;
}
.showRowTag{
  margin-left: 5px;
}
</style>
